package org.mango.action;

import com.alibaba.fastjson.JSONObject;
import com.mango.validator.util.ValidUtil;
import org.mango.base.BaseAction;
import org.mango.bean.Tag;
import org.mango.bean.User;
import org.mango.id.Tools;
import org.mango.service.TagService;
import org.mango.util.UserUtil;
import org.mango.validator.TagNameValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by meigang on 17/10/22.
 */
@RestController
@RequestMapping("/tag")
public class TagAction extends BaseAction{
    @Autowired
    private TagService tagService;
    @Autowired
    private ValidUtil validUtil;
    @Autowired
    private TagNameValidator tagNameValidator;

    @GetMapping("/list")
    public String list(HttpServletRequest req){
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("creator", UserUtil.getSessionUser(req).getId());
        List<Tag> list = tagService.list(map);
        return JSONObject.toJSONString(list);
    }

    @GetMapping("/getById")
    public String getById(String id){
        Tag obj = tagService.getById(id);
        return JSONObject.toJSONString(obj);
    }

    @RequestMapping("/add")
    public String add(Tag obj,HttpServletRequest req){
        obj.setCreateTime(new Date());
        obj.setCreator(UserUtil.getSessionUser(req).getId());
        List<String> msgList = validUtil.validateAll(obj,false,tagNameValidator);
        if(msgList!=null){
            return this.ajaxJson(300,msgList);
        }else {
            obj.setId(Tools.genId()+"");
            tagService.add(obj);
            return this.ajaxJson(200);
        }
    }

    @RequestMapping("/edit")
    public String edit(Tag obj,HttpServletRequest req){
        obj.setLastEditTime(new Date());
        obj.setEditor(UserUtil.getSessionUser(req).getId());
        List<String> msgList = validUtil.validateAll(obj,false,tagNameValidator);
        if(msgList!=null){
            return this.ajaxJson(300,msgList);
        }else {
            tagService.update(obj);
            return this.ajaxJson(200);
        }

    }

    @RequestMapping("/delete")
    public String edit(String id){
        tagService.delete(id);
        return this.ajaxJson(200);
    }

}
